"use strict";

(function() {

  wrapup.windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"]
    .getService(Components.interfaces.nsIWindowMediator); 

  wrapup.ui = {};

  wrapup.ui.pagewatcher = new component.pagewatcherComponent();
  wrapup.ui.button = new component.buttonComponent();
  wrapup.ui.urlbaricon = new component.urlbariconComponent({classes:['dormant']});
  
  wrapup.ui.urlbaricon.toggleClass("dormant", true);

  jQuery(document).on('wrapup-client-pagewatcher-load', function(event) {
    var doc = (!! event.target.ownerDocument) ? event.target.ownerDocument : event.target;

    //wrapup.wrap(doc);
    var watcher = new wrapup.watcher(doc);
    if (watcher && watcher.wrap) {
      watcher.wrap();
    } 
  });

  jQuery(document).on('mozilla-pref-change', function(event, detail) {
    detail = detail || event.detail || (event.originalEvent && event.originalEvent.detail);
    console.log("CHANGE YOU SAY: " + JSON.stringify(detail));

    switch (detail.key) {
      case "server.path":
        if (detail.newval) {
          wrapup.env.server.path = detail.newval;
        }
        break;
      case "format":
        wrapup.env.format = detail.newval;
        break;
      case "usestyle":
        if (detail.newval) {
          console.log("EMIT");
          document.dispatchEvent(new CustomEvent('register-stylesheet', {bubbles:true,detail:{stylesheet:"wrapped.css"}}));
          console.log("EMITTED");
        } else {
          //unregister
        }
        break;
      default:
    }
  });

  jQuery(document).on('wrapup-show-ui', function(event) {
    wrapup.ui.urlbaricon.toggleClass("dormant", false);
  });

  jQuery(document).on('wrapup-client-urlbaricon-click', function(event) {
    wrapup.ui.urlbaricon.toggleClass("dormant", true);
  });

  jQuery(document).on('wrapup-applied-wrapper', function(event) {
    wrapup.ui.urlbaricon.toggleClass("wrapped", true);
  });

  jQuery(document).on('wrapup-client-button-click', function(event) {
    console.log("CLEEK");

    //console.log("#: " + window.BrowserApp.tabs.length);

    var callback = function(detail) {
      console.log("SERVERPATH: " + JSON.stringify(detail));
    };
      
    document.dispatchEvent(new CustomEvent('wrapup-show-ui', {detail:{},bubbles:true}));  
    document.dispatchEvent(new CustomEvent("mozilla-get-pref", {bubbles:true,detail:{key:"server.path",callback:callback}}));
    document.dispatchEvent(new CustomEvent("mozilla-get-pref", {bubbles:true,detail:{key:"server.path"}}));
  });

}());
